//
//  LXDSongViewController.m
//  BLDMusics
//
//  Created by lxd on 16/3/18.
//  Copyright © 2016年 李晓丹. All rights reserved.
//

#import "LXDSongViewController.h"

@interface LXDSongViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

/**底层collection*/
@property (nonatomic, retain) UICollectionView *collection;

/**源数据数组*/
@property (nonatomic, retain) NSMutableArray *modelArr;

/**接口最新和最热的交换值*/
@property (nonatomic, retain) NSString *segStr;

/**刷新页数*/
@property (nonatomic, assign) NSInteger page;

/**加载菊花的视图*/
@property (nonatomic, retain) UIView *hudView;
/**
 *  block传值，
 */
@property (nonatomic, retain) NSString *str;

@end

@implementation LXDSongViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"歌单广场";
    [self createHeader];
    [self createCollection];
    [self dataHandle];
    [self addFooter];
    
}



#pragma mark - 创建头标栏
- (void)createHeader {
    // 全部button
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 50)];
    [self.view addSubview:headerView];
    UIButton *allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake(15, 13, 70, 30);
    [allButton setTitle:@"全部>" forState:UIControlStateNormal];
    [allButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    allButton.layer.borderWidth = 1;
    allButton.layer.borderColor = [UIColor grayColor].CGColor;
    allButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [headerView addSubview:allButton];
    [allButton addTarget:self action:@selector(allAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 最热和最新
    UISegmentedControl *segment = [[UISegmentedControl alloc] initWithItems:@[@"最热", @"最新"]];
    [headerView addSubview:segment];
    [segment addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    segment.selectedSegmentIndex = 0;
    segment.frame = CGRectMake(SCREEN_WIDTH - 120, 13, 110, 30);
    [segment setTintColor:[UIColor redColor]];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIColor darkGrayColor],NSForegroundColorAttributeName,[UIFont fontWithName:@"AppleGothic"size:16],NSFontAttributeName ,nil];
    [segment setTitleTextAttributes:dic forState:UIControlStateNormal];
    
}
#pragma mark - 创建CollectionView
- (void)createCollection {
    self.modelArr = [NSMutableArray array];
    _page = 1;
    _segStr = @"最热";
    _str = @"";
    
    // collection
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 10;
    layout.minimumLineSpacing = 15;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    layout.itemSize = CGSizeMake((SCREEN_WIDTH - 30) / 2, (SCREEN_WIDTH - 30) / 2 + 20);
    // 分区悬停
    layout.sectionHeadersPinToVisibleBounds = YES;
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 50, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64 - 70) collectionViewLayout:layout];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collection];
    // 注册
    [self.collection registerClass:[LXDSongCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
    
    // 加载菊花的视图
    self.hudView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 150)];
    _hudView.center = CGPointMake(self.view.center.x, _collection.frame.size.height / 2);
    [self.view addSubview:_hudView];
    
}



#pragma mark - 返回每个分区item的数量
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return _modelArr.count;
}
#pragma mark - 返回item
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    LXDSongCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    LXDSongModel *model = _modelArr[indexPath.row];
    cell.model = model;
    return cell;
}
#pragma mark -点击cell
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    LXDSongModel *model = _modelArr[indexPath.row];
    BYJCarouselViewController *vc = [[BYJCarouselViewController alloc] init];
    vc.value = [model.quan_id stringValue];
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - segment方法
- (void)segmentAction:(UISegmentedControl *)seg {
   
    if (seg.selectedSegmentIndex == 0) {
        _segStr = @"最热";
        _page = 1;
    } else {
        _segStr = @"最新";
        _page = 1;
    }
    // 让数组清空，重新去给collection赋值
     [_modelArr removeAllObjects];
    [_collection reloadData];
    _collection.contentOffset = CGPointMake(0, 0);
    [self dataHandle];
}

#pragma mark - 点击全部的方法
- (void)allAction {
    LXDAllSOngViewController *vc = [[LXDAllSOngViewController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    vc.block = ^(NSString *str) {
        if ([str isEqualToString:@""]) {
            _str = @"";
        } else {
            _str = [NSString stringWithFormat:@"|%@", str];
        }
        _collection.contentOffset = CGPointMake(0, 0);
        [_modelArr removeAllObjects];
        [_collection reloadData];
        [self dataHandle];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 数据解析
- (void)dataHandle {
    
    // 菊花加载
    [MBProgressHUD showHUDAddedTo:_hudView animated:YES];
    
    NSString *interface = [NSString stringWithFormat:@"http://search.dongting.com/songlist/search?q=tag:%@%@&page=%ld&size=10", _segStr, _str,  _page];
    
    [APPTools GETWithURL:interface par:nil success:^(id responseObject) {
        NSArray *tempArr =  [LXDSongModel modelHandleWithArray:responseObject[@"data"]];
        
        [self.modelArr addObjectsFromArray:tempArr];
        [_collection reloadData];
        
        // 结束上拉刷新
        [_collection.mj_footer endRefreshing];
        
        // 数据下来以后，菊花消失
        [MBProgressHUD hideHUDForView:_hudView animated:YES];
        
    } filed:^(NSError *error) {
        NSLog(@"%@", error);
    }];
}

#pragma mark - 刷新
- (void)addHeader {
    _page = 1;
    //    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    //    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandle)];
    //
    //    // 图片数组
    //    NSMutableArray *imageArr = [NSMutableArray array];
    //    for (NSInteger i = 0; i < 3; i++) {
    //        NSString *str = [NSString stringWithFormat:@"lxd%ld.png", i + 1];
    //        UIImage *imag = [UIImage imageNamed:str];
    //        [imageArr addObject:imag];
    //    }
    //    // 设置普通状态的动画图片
    //    [header setImages:imageArr forState:MJRefreshStateIdle];
    //    // 设置即将刷新状态的动画图片(一松开就会刷新的状态)
    //    [header setImages:imageArr forState:MJRefreshStatePulling];
    //    // 设置正在刷新状态的图片
    //    [header setImages:imageArr forState:MJRefreshStateRefreshing];
    //    // 设置header
    //    self.collection.mj_header = header;
    //
    
    
}
- (void)addFooter {
    // 上拉刷新-默认
    self.collection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page ++;
        [self dataHandle];
    }];
    _collection.mj_footer.automaticallyHidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
